library(dplyr)
library(ProbBayes)

bayese_poster <- function(d) {
  d$Product = d$Likelihood * d$Prior
  d$Posterior = d$Product / sum(d$Product)
  return(d)
}

exp_f <- function(n, meau, sd, meanu_ob) {
  m = -n/(2*sd**2)*((meau-meanu_ob)**2)
  exp(m)
}

(17.2-15)**2

m <- -1 * 20/(2*16) *(17.2-15)**2

exp(m)

exp_f(20, 17.2, 4, 15)

df <- data.frame(mu=seq(15,22,1),
                 Prior=rep(1/8,8))

observed_value <- 15.1
standard_deviation <- 4

df$Likelihood <- dnorm(observed_value, mean=df$mu, sd=standard_deviation)


df <- bayese_poster(df)

df <- round(df, 4)


df1 <- data.frame(mu=seq(15,22,1),
                 Prior=rep(1/8,8))

df1 %>%
  mutate(Likelihood = exp_f(20, 17.2, 4, mu)) %>%
  bayese_poster() %>%
  round(4) -> df1

prior_post_plot(df1, Color = "blue") +
  labs(title = "Posterior Distribution with Exponential Likelihood",
       x = "Mean (mu)",
       y = "Density") +
  theme_minimal()


df2 <- data.frame(mu=seq(15,22,1),
                  Prior=rep(1/8,8))


df2 <- df2 %>%
  mutate(Likelihood = dnorm(mu, 17.2, 4/sqrt(20))) %>%
  bayese_poster() %>%
  round(4)


observed_data <- c(15.1, 11.8, 21.0, 22.7, 18.6, 16.2, 11.1, 13.2, 20.4, 19.2,
                   21.2, 14.3, 18.6, 16.8, 20.3, 19.9, 15.0, 13.4, 19.9, 15.3)

mean(observed_data)

cal_all <- function(mu, sd) {
  all_m <- dnorm(observed_data, mu, sd)
  m <- prod(all_m)
  m
}

C1 <- 1/sqrt(2*pi)

exp1 <- function(obv, mu, sd) {
  t1 <- exp(-1/(2 * sd**2) * (obv - mu)**2)
  C1/sd * t1
}

dnorm(15.1, 22, 4)
exp1(15.1, 22, 4)

# sum(go1)
# mean(go1)
# 
# prod(go1)

df3 <- data.frame(mu=seq(15,22,1),
                  Prior=rep(1/8,8))

df3 <- df3 %>%
  rowwise() %>%
  mutate(Likelihood = cal_all(mu, 4)) %>%
  bayese_poster() %>%
  round(4)

sum(df3$Product)

df3$Product[1] / sum(df3$Product)


prior_post_plot(df1, Color = "blue") +
  theme_minimal()


prior_post_plot(df3, Color = "blue") +
  theme_minimal()
# df3 <- df3 %>% round(6)



# df4 <- df3 %>%
#   mutate(Likelihood = cal_all(mu, 4)) %>%
#   bayese_poster()
# round(4)



  
